package com.czxy.Servlet;

import cn.itcast.servlet.BaseServlet;
import com.czxy.Service.UserService;
import com.czxy.domain.User;
import com.czxy.utils.CreateImageCode;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @version v 1.0
 * @Author kami
 * @Date 2019/4/28
 */
@WebServlet("/UserLoginServlet")
public class UserServlet extends BaseServlet {
//    {HttpSession session = getRequest().getSession(false);}
    private UserService us = new UserService();
    //设置注册的错误信息
    public static String errorRegister = "";

    //登录验证码
    public void getVcImg() throws IOException {
        CreateImageCode imageCode = new CreateImageCode();
        BufferedImage buffImg = imageCode.getBuffImg();
        String code = imageCode.getCode();
        this.getRequest().getSession().setAttribute("vcCode", code);
        System.out.println("登录验证码--->" + getRequest().getSession().getAttribute("vcCode"));
        imageCode.write(getResponse().getOutputStream());
    }

    //登录
    public void login() throws IOException, ServletException {
        HttpSession session = getRequest().getSession(false);
        String vcCode = (String) session.getAttribute("vcCode");
        String vc = this.getRequest().getParameter("vc"); //获取传递过来的验证码
        Cookie cookie = new Cookie("TheCookieN", "0");  //设置cookie 之后浏览器就不会弹出那个主页面弹窗
        getResponse().addCookie(cookie);
        if (vcCode.equals(vc)) {
            String loginName = this.getRequest().getParameter("loginName");
            String password = this.getRequest().getParameter("password");
            User userStandby = us.login(loginName, password);
            cookie.setMaxAge(60 * 2);
            if (userStandby != null) {
                this.getRequest().getSession().setAttribute("loginUser", userStandby);
                getResponse().getWriter().print("{\"message\":\"登陆成功!\",\"flag\":true}");
                return;
            } else {
                //用户名密码错误
//                this.getRequest().setAttribute("loginMsg", "用户名或密码错误");
                getResponse().getWriter().print("{\"message\":\"用户名或密码错误\",\"flag\":false}");
                return;
            }
        } else {
            getResponse().getWriter().print("{\"message\":\"验证码错误!\",\"flag\":false}");
            return;
        }
    }


    //注册框验证码
    public void vcCodeByResister() throws IOException {
        CreateImageCode imageCode = new CreateImageCode();
        BufferedImage buffImg = imageCode.getBuffImg();
        String code = imageCode.getCode();
        this.getRequest().getSession().setAttribute("vcRegisterCode", code);
        System.out.println("注册验证码--->" + code);
        imageCode.write(getResponse().getOutputStream());
    }


    //注册
    public void insert() throws ServletException, IOException {
        //获取参数
        User user = toBean(User.class);
        String pwd = this.getRequest().getParameter("pwd");
        String registerCode = this.getRequest().getParameter("registerCode");
        //判断验证码是否正确
        String vcRegisterCode = (String) getRequest().getSession().getAttribute("vcRegisterCode");
        if (!registerCode.equalsIgnoreCase(vcRegisterCode)) {
            //验证码错误
            getResponse().getWriter().print("{\"message\":\"验证码输入错误\",\"flag\":false}");
            return;
        } else {

            //验证码正确  判断输入格式
            if (isChinese(user.getLoginName())){
                //loginname为中文,不允许注册
                getResponse().getWriter().print("{\"message\":\"登录名不允许为中文!\",\"flag\":false}");
                return;
            }

            if (isChinese(user.getPassword())){
                if (!IsPasswLength(user.getPassword())){
                    //密码验证长度6-18长度
                    getResponse().getWriter().print("{\"message\":\"密码长度不规范(6-18个长度)!\",\"flag\":false}");
                    return;
                }
                //密码中文
                getResponse().getWriter().print("{\"message\":\"密码不允许为中文!\",\"flag\":false}");
                return;
            }

            //验证手机
            if (!IsTelephone(user.getPhone()+"")){
                getResponse().getWriter().print("{\"message\":\"手机格式错误!\",\"flag\":false}");
                return;
            }

            //验证邮箱
            if (!isEmail(user.getEmail())){
                //邮箱格式不正确
                getResponse().getWriter().print("{\"message\":\"邮箱格式不正确!\",\"flag\":false}");
                return;
            }

            //调用service方法
            User u = us.insert(user, pwd);
            //判断是否注册成功
            if (u != null) {
               getResponse().getWriter().print("{\"message\":\"注册成功!\",\"flag\":true}");
               return;
            } else {
                System.out.println(errorRegister);
                getResponse().getWriter().print("{\"message\":\""+errorRegister+"!\",\"flag\":false}");
                return;
            }
        }
    }

    /**
     * 验证输入密码长度 (6-18位)
     * @return 如果是符合格式的字符串,返回 <b>true </b>,否则为 <b>false </b>
     */
    public static boolean IsPasswLength(String str) {
        String regex = "^\\d{6,18}$";
        return match(regex, str);
    }

    /**
     * 验证邮箱
     *
     * @param
     * @return 如果是符合的字符串,返回 <b>true </b>,否则为 <b>false </b>
     */
    public static boolean isEmail(String str) {
        String regex = "^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        return match(regex, str);
    }
    /**
     * 判断该字符串是否为中文
     * @param string
     * @return
     */
    public static boolean isChinese(String string){
        int n = 0;
        for(int i = 0; i < string.length(); i++) {
            n = (int)string.charAt(i);
            if(!(19968 <= n && n <40869)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 验证输入密码条件(字符与数据同时出现)
     * @return 如果是符合格式的字符串,返回 <b>true </b>,否则为 <b>false </b>
     */
    public static boolean IsPassword(String str) {
        String regex = "[A-Za-z]+[0-9]";
        return match(regex, str);
    }



    /**
     * @param regex
     * 正则表达式字符串
     * @param str
     * 要匹配的字符串
     * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
     */
    private static boolean match(String regex, String str) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }
    /**
     * 验证电话号码
     *
     * @param
     * @return 如果是符合格式的字符串,返回 <b>true </b>,否则为 <b>false </b>
     */
    public static boolean IsTelephone(String phone) {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        if (phone.length() != 11) {
            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
            return isMatch;
        }
    }
}
